import java.util.Random;

class Solution {
    public int[] inventoryManagement(int[] stock, int cnt) {
        qsort(stock,0,stock.length-1,cnt);
        int[] ret=new int[cnt];
        for(int i=0;i<cnt;i++) ret[i]=stock[i];
        return ret;
    }

    public void qsort(int[] nums,int l,int r,int k){
        if(l>=r) return;
        int key=nums[new Random().nextInt(r-l+1)+l];
        int left=l-1,right=r+1,i=l;
        while(i<right){
            if(nums[i]<key) swap(nums,i++,++left);
            else if(nums[i]==key) i++;
            else swap(nums,i,--right);
        }

        int a=left-l+1,b=right-left-1,c=r-right+1;

        if(a>k)  qsort(nums,l,left,k);
        else if(k<=(a+b)) return;
        else qsort(nums,right,r,k-a-b);

    }

    public void swap(int[] nums,int i,int j){
        int t=nums[i];
        nums[i]=nums[j];
        nums[j]=t;
    }
}



class Solution1 {
    public int[] sortArray(int[] nums) {
        func(nums,0,nums.length-1);
        return nums;
    }

    public void func(int[] nums,int l,int r){
        if(l>=r) return;
        int mid=(l+r)/2;
        func(nums,l,mid);
        func(nums,mid+1,r);
        func1(nums,l,r,mid);


    }

    public void func1(int[] nums,int l,int r,int mid){
        int i=l,j=mid+1,k=0;
        int[] arr= new int[r-l+1];
        while(i<=mid&&j<=r){
            if(nums[i]<=nums[j]) arr[k++]=nums[i++];
            else arr[k++]=nums[j++];
        }

        while(i<=mid){
            arr[k++]=nums[i++];
        }

        while(j<=r){
            arr[k++]=nums[j++];
        }

        for(i=0;i<r-l+1;i++){
            nums[l+i]=arr[i];
        }



    }

    public void swap(int[] nums,int i,int j){
        int t=nums[i];
        nums[i]=nums[j];
        nums[j]=t;

    }
}
